package com.fwj.authorization.security;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fwj.authorization.staff.entity.SysPermission;
import com.fwj.authorization.staff.entity.SysRole;
import com.fwj.authorization.staff.entity.SysUser;
import com.fwj.authorization.staff.service.SysUserService;
import com.fwj.base.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录成功处理器
 *
 * @author fwj
 * @date 2025/03/18
 */
@Slf4j
@Component("authenticationSuccessHandler")
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private SysUserService sysUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        log.info("登录成功!");
        response.setContentType("application/json;charset=UTF-8");
        SysUser user = sysUserService.getUserByUsername(authentication.getName());
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        log.info("用户存在，用户:{}", authentication.getName());
        List<SysRole> roleList = sysUserService.getRoleListByUsername(authentication.getName());
        List<SysPermission> permissionList = sysUserService.getPermissionListByUsername(authentication.getName());
        List<SimpleGrantedAuthority> userGrantedAuthorities = createAuthorities(roleList);
        List<String> rolePrem = createRolePrem(permissionList);
        //返回数据对象(手动已加密)
        LoginUser loginUser = new LoginUser(user.getId(),
                null,
                "FWJ",
                user.getUsername(),
                user.getRealName(),
                user.getPwd(),
                true, true, true, true,
                userGrantedAuthorities,
                user.getStatus(),
                rolePrem);
        Map<String, Object> map = BeanUtil.beanToMap(loginUser);
        String token = JwtTokenUtil.generateToken(map);
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("authentication", authentication);
        response.getWriter().write(objectMapper.writeValueAsString(R.ok(tokenMap)));

        //更新登录时间
        sysUserService.updateLastLoginTime(authentication.getName());
    }

    private List<String> createRolePrem(List<SysPermission> permissionList) {
        List<String> rolePrem = new ArrayList<>();
        for (SysPermission sysPermission : permissionList) {
            String roleCode = sysPermission.getRoleCode();
            String url = sysPermission.getUrl();
            if (roleCode != null && url != null) {
                // 角色权限码 roleCode[/user/page]
                rolePrem.add(roleCode + "[" + url + "]");
            }
        }
        return rolePrem;
    }

    private List<SimpleGrantedAuthority> createAuthorities(List<SysRole> roleList) {
        List<SimpleGrantedAuthority> userGrantedAuthorities = new ArrayList<>();
        for (SysRole role : roleList) {
            userGrantedAuthorities.add(new SimpleGrantedAuthority(role.getCode()));
            log.info("role:{}", role);
        }
        return userGrantedAuthorities;
    }
}
